package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"fmt"
	// "io/ioutil"
	"strings"
	"crypto/rand"
	// "path/filepath"
	// "os"
	// "mime"
	// "bytesToHexString"
	"strconv"
)

// 招聘资讯页获取所有资讯
func GetAllRecruit(c *gin.Context){
	rows, err := Db.Query("SELECT * FROM recruits")
	fmt.Println(rows)
	
	if err != nil {
		fmt.Println(err)
		return
	}
	defer rows.Close()
	recruits := make([]Recruit, 0)
	for rows.Next() {
		var recruit Recruit
		rows.Scan(&recruit.Job,&recruit.Address,&recruit.Company,&recruit.Mode,&recruit.People,&recruit.Description,&recruit.Skill,&recruit.Method,&recruit.Allow,&recruit.File,&recruit.Tag)
		fmt.Println(recruit.Tag)
		recruits = append(recruits, recruit)
	}
	if err = rows.Err(); err != nil {
		fmt.Println(err)
		return
	}
	c.JSON(http.StatusOK, recruits)
}

func RandToken(num int) string {
    b := make([]byte, num)
    rand.Read(b)
    return fmt.Sprintf("%x", b)
}
// 发布资讯
func PostRecruit(c *gin.Context){
	var recruit Recruit
	err := c.BindJSON(&recruit)
	if err != nil {
		fmt.Println(err)
		return
	}
	job := recruit.Job
	address := recruit.Address
	company := recruit.Company
	mode := recruit.Mode
	people := recruit.People
	description := recruit.Description
	skill := recruit.Skill
	method := recruit.Method
	allow := recruit.Allow
	file := recruit.File
	newAllow := 0
	tag := RandToken(12)
	if allow == true {
		newAllow = 1
	}
	rs, err := Db.Exec("INSERT INTO recruits(job, address, company, mode, people, description, skill, method, allow, file, tag) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", job, address, company, mode, people, description, skill, method, newAllow, file, tag)
	fmt.Println(rs)
	if err != nil {
		fmt.Println(err)
		return	
	}

	msg := fmt.Sprintf("insert successful")
	c.JSON(http.StatusOK, gin.H{
	"msg": msg,
	})
}

// 上传资讯附件
func PostReleaseFile(c *gin.Context) {
	PostFile(c,"recruitfile/")
}

// 上传简历附件
func PostResumeFile(c *gin.Context){
	PostFile(c,"resumefile/")
}
// 上传附件
func PostFile(c *gin.Context,path string){
	file, err := c.FormFile("file")
	c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%s", file.Filename))
	if err!= nil {
		fmt.Println(err)
		return
	} else {
		ss := strings.Split(file.Filename, ".")
		newName := "" + RandToken(12) + "."+ss[len(ss)-1]
		err = c.SaveUploadedFile(file, path+newName)
		if err!= nil {
			fmt.Println(err)
			return
		}
		c.JSON(http.StatusOK, gin.H{
				"msg": newName,
			})
	}
}

// 上传简历
func PostResume(c *gin.Context){
	var resume Resume
	err := c.BindJSON(&resume)
	if err != nil {
		fmt.Println(err)
		return
	}
	job := resume.Job
	name := resume.Name
	content := resume.Content
	id := resume.Id
	file := resume.File
	fmt.Println(id)
	rs, err := Db.Exec("INSERT INTO resumes(job, name, content, id, file) VALUES (?, ?, ?, ?, ?) on duplicate key update job = ?,name = ?,content = ?,file = ?", job, name, content, id, file, job, name, content, file)
	fmt.Println(rs)
	if err != nil {
		fmt.Println(err)	
		return
	}
	msg := fmt.Sprintf("insert successful")
	c.JSON(http.StatusOK, gin.H{
	"msg": msg,
	})
}

// 我来内推页获取所有简历
func GetAllResume(c *gin.Context){
	rows, err := Db.Query("SELECT * FROM resumes")
	fmt.Println(rows)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer rows.Close()
	resumes := make([]Resume, 0)
	for rows.Next() {
		var resume Resume
		rows.Scan(&resume.Job,&resume.Name,&resume.Content,&resume.Id,&resume.File)
		resumes = append(resumes, resume)
	}
	if err = rows.Err(); err != nil {
		fmt.Println(err)
		return
	}
	// 返回数据 第二个参数可以是任意对象 json方法将该对象序列化为json返回 第一个是http状态码
	c.JSON(http.StatusOK, resumes)
}

// 贴心留言获取所有留言
func GetAllWord(c *gin.Context){
	rows, err := Db.Query("SELECT * FROM words")
	fmt.Println(rows)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer rows.Close()
	words := make([]Word, 0)
	for rows.Next() {
		var word Word
		rows.Scan(&word.Id,&word.Content,&word.Name,&word.Date,&word.Allow,&word.Tag)
		words = append(words, word)
	}
	if err = rows.Err(); err != nil {
		fmt.Println(err)
		return
	}
	// 返回数据 第二个参数可以是任意对象 json方法将该对象序列化为json返回 第一个是http状态码
	c.JSON(http.StatusOK, words)
}

// 发布留言
func PostWord(c *gin.Context){
	var word Word
	err := c.BindJSON(&word)
	if err != nil {
		fmt.Println(err)
		return
	}
	id := word.Id
	name := word.Name
	content := word.Content
	date := word.Date
	allow := word.Allow
	newAllow := 0
	tag := RandToken(12)
	if allow == true {
		newAllow = 1
	}
	rs, err := Db.Exec("INSERT INTO words(id, name, content, date, allow, tag) VALUES (?, ?, ?, ?, ?, ?)", id, name, content, date, newAllow, tag)
	fmt.Println(rs)
	if err != nil {
		fmt.Println(err)	
		return
	}

	msg := fmt.Sprintf("insert successful")
	c.JSON(http.StatusOK, gin.H{
	"msg": msg,
	})
}

// 注册页面 注册用户
func PostRegister(c *gin.Context){
	var user User
	err := c.BindJSON(&user)
	if err != nil {
		fmt.Println(err)
		return 
	}
	id := user.Id
	name := user.Name
	password := user.Password
	email := user.Email
	schoolId := user.SchoolId
	identity := user.Identity
	question := user.Question
	answer := user.Answer
	allow := user.Allow
	rs, err := Db.Exec("INSERT INTO users(id, name, password, email, schoolId, identity, question, answer, allow) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", id, name, password, email, schoolId, identity, question, answer, allow)
	fmt.Println(rs)
	if err != nil {
		fmt.Println(err)	
		return 
	}

	msg := fmt.Sprintf("insert successful")
	c.JSON(http.StatusOK, gin.H{
	"msg": msg,
	})
}

// 登录 判断用户登录
func PostLog(c *gin.Context){
	var log Log
	var user User
	err := c.BindJSON(&log)
	if err != nil {
		fmt.Println(err)
		return 
	}
	password := log.Password
	email := log.Email
	newerr := Db.QueryRow("SELECT password, allow, name, identity, id FROM users WHERE email=?", email).Scan(
		&user.Password, &user.Allow, &user.Name, &user.Identity, &user.Id,
	   )
	   
	if newerr != nil {
		fmt.Println(err)	
		return 
	}
	if user.Allow == 1&&user.Password ==password {
		msg := "allow"
		c.JSON(http.StatusOK, gin.H{
		"msg": msg,
		"name": user.Name,
		"type": user.Identity,
		"id": user.Id,
		})
	} else if user.Allow == 0&&user.Password ==password {
		msg := "noallow"
		c.JSON(http.StatusOK, gin.H{
		"msg": msg,
		})
	}
	
}

// 个人中心页面 获取所有信息
func GetAllPersonal(c *gin.Context){
	id := c.Query("id")
	row1s, err := Db.Query("SELECT * FROM peopleapply where id=?", id)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer row1s.Close()
	applys := make([]Apply, 0)
	for row1s.Next() {
		var apply Apply
		row1s.Scan(&apply.Company,&apply.Job,&apply.Date,&apply.Remarks,&apply.Id,&apply.Tag)
		applys = append(applys, apply)
	}
	if err = row1s.Err(); err != nil {
		fmt.Println(err)
		return
	}

	row2s, err := Db.Query("SELECT * FROM peopleschedule where id=?", id)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer row2s.Close()
	schedules := make([]Schedule, 0)
	for row2s.Next() {
		var schedule Schedule
		row2s.Scan(&schedule.Todo,&schedule.Date,&schedule.Remarks,&schedule.Id,&schedule.Tag)
		schedules = append(schedules, schedule)
	}
	if err = row2s.Err(); err != nil {
		fmt.Println(err)
		return
	}

	row3s, err := Db.Query("SELECT * FROM peoplenote where id=?", id)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer row3s.Close()
	notes := make([]Note, 0)
	for row3s.Next() {
		var note Note
		row3s.Scan(&note.Head,&note.Content,&note.Id,&note.Tag)
		notes = append(notes, note)
	}
	if err = row3s.Err(); err != nil {
		fmt.Println(err)
		return
	}
	// 返回数据 第二个参数可以是任意对象 json方法将该对象序列化为json返回 第一个是http状态码
	c.JSON(http.StatusOK, gin.H{
		"apply": applys,
		"schedule": schedules,
		"note": notes,
	})
}

// 个人中心 增加apply
func PostAddApply(c *gin.Context){
	var apply Apply
	err := c.BindJSON(&apply)
	if err != nil {
		fmt.Println(err)
		return 
	}
	id := apply.Id
	company := apply.Company
	job := apply.Job
	date := apply.Date
	remarks := apply.Remarks
	tag := RandToken(12)
	rs, err := Db.Exec("INSERT INTO peopleapply(company, job, date, remarks, id, tag) VALUES (?, ?, ?, ?, ?, ?)", company, job, date, remarks, id, tag)
	fmt.Println(rs)
	if err != nil {
		fmt.Println(err)	
		return 
	}

	msg := fmt.Sprintf("添加成功")
	c.JSON(http.StatusOK, gin.H{
	"msg": msg,
	})
}

// 个人中心 增加schedule
func PostAddSchedule(c *gin.Context){
	var schedule Schedule
	err := c.BindJSON(&schedule)
	if err != nil {
		fmt.Println(err)
		return 
	}
	todo := schedule.Todo
	date := schedule.Date
	remarks := schedule.Remarks
	id := schedule.Id
	tag := RandToken(12)
	rs, err := Db.Exec("INSERT INTO peopleschedule(todo, date, remarks, id, tag) VALUES (?, ?, ?, ?, ?)", todo, date, remarks, id, tag)
	fmt.Println(rs)
	if err != nil {
		fmt.Println(err)	
		return 
	}

	msg := fmt.Sprintf("添加成功")
	c.JSON(http.StatusOK, gin.H{
	"msg": msg,
	})
}

// 个人中心 增加note
func PostAddNote(c *gin.Context){
	var note Note
	err := c.BindJSON(&note)
	if err != nil {
		fmt.Println(err)
		return 
	}
	head := note.Head
	content := note.Content
	id := note.Id
	tag := RandToken(12)
	rs, err := Db.Exec("INSERT INTO peoplenote(head, content, id, tag) VALUES (?, ?, ?, ?)", head, content, id, tag)
	fmt.Println(rs)
	if err != nil {
		fmt.Println(err)	
		return 
	}

	msg := fmt.Sprintf("添加成功")
	c.JSON(http.StatusOK, gin.H{
	"msg": msg,
	})
}

// 个人中心 保存apply
func PostChangeApply(c *gin.Context){
	var apply Apply
	err := c.BindJSON(&apply)
	if err != nil {
		fmt.Println(err)
		return 
	}
	company := apply.Company
	job := apply.Job
	date := apply.Date
	remarks := apply.Remarks
	tag := apply.Tag

	stmt, err := Db.Prepare("UPDATE peopleapply SET company=?, job=?, date=?, remarks=?  WHERE tag=?")
  	defer stmt.Close()
	if err != nil {
	fmt.Println(err)
	return
	}
	rs, err := stmt.Exec(company, job, date, remarks, tag)
	if err != nil {
		fmt.Println(err)
		return
	}
	ra, err := rs.RowsAffected()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(ra)
	msg := fmt.Sprintf("保存成功")
	c.JSON(http.StatusOK, gin.H{
	"msg": msg,
	})
}

// 个人中心 保存schedule
func PostChangeSchedule(c *gin.Context){
	var schedule Schedule
	err := c.BindJSON(&schedule)
	if err != nil {
		fmt.Println(err)
		return 
	}
	todo := schedule.Todo
	date := schedule.Date
	remarks := schedule.Remarks
	tag := schedule.Tag

	stmt, err := Db.Prepare("UPDATE peopleschedule SET todo=?, date=?, remarks=?  WHERE tag=?")
  	defer stmt.Close()
	if err != nil {
	fmt.Println(err)
	return
	}
	rs, err := stmt.Exec(todo, date, remarks, tag)
	if err != nil {
		fmt.Println(err)
		return
	}
	ra, err := rs.RowsAffected()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(ra)
	msg := fmt.Sprintf("保存成功")
	c.JSON(http.StatusOK, gin.H{
	"msg": msg,
	})
}

// 个人中心 保存note
func PostChangeNote(c *gin.Context){
	var note Note
	err := c.BindJSON(&note)
	if err != nil {
		fmt.Println(err)
		return 
	}
	head := note.Head
	content := note.Content
	tag := note.Tag

	stmt, err := Db.Prepare("UPDATE peoplenote SET head=?, content=? WHERE tag=?")
  	defer stmt.Close()
	if err != nil {
	fmt.Println(err)
	return
	}
	rs, err := stmt.Exec(head, content, tag)
	if err != nil {
		fmt.Println(err)
		return
	}
	ra, err := rs.RowsAffected()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(ra)
	msg := fmt.Sprintf("保存成功")
	c.JSON(http.StatusOK, gin.H{
	"msg": msg,
	})
}

// 个人中心 修改密码
func ChangePassword(c *gin.Context){
	var changePassword Changepassword
	err := c.BindJSON(&changePassword)
	if err != nil {
		fmt.Println(err)
		return 
	}
	new := changePassword.New
	old := changePassword.Old
	id := changePassword.Id
	var password string
	newerr := Db.QueryRow("SELECT password FROM users WHERE id=?", id).Scan(
		&password,
	   )
	if newerr != nil {
	fmt.Println(newerr)
	return
	}
	if password == old {
		stmt, err := Db.Prepare("UPDATE users SET password=? WHERE id=?")
		defer stmt.Close()
		if err != nil {
			fmt.Println(err)
			return
		}
		rs, err := stmt.Exec(new,id)
		if err != nil {
			fmt.Println(err)
			return
		}
		ra, err := rs.RowsAffected()
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(ra)
		c.JSON(http.StatusOK, gin.H{
			"status":true,
			"msg": "修改成功，请重新登录",
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"status":false,
			"msg": "修改失败，旧密码输入有误",
			})
	}
}

// 得到所有用户
func GetAllUser(c *gin.Context){
	rows, err := Db.Query("SELECT * FROM users")
	fmt.Println(rows)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer rows.Close()
	users := make([]User, 0)
	for rows.Next() {
		var user User
		rows.Scan(&user.Id,&user.Name,&user.Password,&user.Email,&user.SchoolId,&user.Identity,&user.Question,&user.Answer,&user.Allow)
		users = append(users, user)
	}
	if err = rows.Err(); err != nil {
		fmt.Println(err)
		return
	}
	// 返回数据 第二个参数可以是任意对象 json方法将该对象序列化为json返回 第一个是http状态码
	c.JSON(http.StatusOK, users)
}

// 后台管理页面 发布
func PostManage(c *gin.Context){
	var release Release
	err := c.BindJSON(&release)
	if err != nil {
		fmt.Println(err)
		return 
	}
	mold := release.Mold
	msg :=  ""
	status := false
	if mold == "user" {
		id, err := strconv.Atoi(release.Tag)
		rs, err := Db.Exec("UPDATE users SET allow=1 WHERE id=?",id)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(rs)
		status = true
		msg = "发布成功！"
	} else if mold == "recruit" {
		tag := release.Tag
		fmt.Println("recruits")
		rs, err := Db.Exec("UPDATE recruits SET allow=1 WHERE tag=?",tag)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(rs)
		status = true
		msg = "发布成功！"
	} else if mold == "word" {
		tag := release.Tag
		rs, err := Db.Exec("UPDATE words SET allow=1 WHERE tag=?",tag)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(rs)
		status = true
		msg = "发布成功！"
	}
	c.JSON(http.StatusOK, gin.H{
		"status": status,
		"msg": msg,
	})
}

// 后台管理页面 删除
func PostManageRemove(c *gin.Context){
	var remove Release
	err := c.BindJSON(&remove)
	if err != nil {
		fmt.Println(err)
		return 
	}
	mold := remove.Mold
	msg :=  ""
	status := false
	if mold == "user" {
		id, err := strconv.Atoi(remove.Tag)
		rs, err := Db.Exec("DELETE FROM users WHERE id=?", id)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(rs)
		status = true
		msg = "删除成功！"
	} else if mold == "recruit" {
		tag := remove.Tag
		fmt.Println("recruits")		
		rs, err := Db.Exec("DELETE FROM recruits WHERE tag=?", tag)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(rs)
		status = true
		msg = "删除成功！"
	} else if mold == "word" {
		tag := remove.Tag
		rs, err := Db.Exec("DELETE FROM words WHERE tag=?", tag)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(rs)
		status = true
		msg = "删除成功！"
	}
	c.JSON(http.StatusOK, gin.H{
		"status": status,
		"msg": msg,
	})
}

// 找回密码
func FindPassword(c *gin.Context){
	var findPassword Findpassword
	err := c.BindJSON(&findPassword)
	if err != nil {
		fmt.Println(err)
		return 
	}
	email := findPassword.Email
	question := findPassword.Question
	answer := findPassword.Answer
	var questionVal string
	var answerVal string
	newerr := Db.QueryRow("SELECT question, answer FROM users WHERE email=?", email).Scan(
		&questionVal, &answerVal,
	   )
	if newerr != nil {
	fmt.Println(newerr)
	return
	}
	if question == questionVal && answer == answerVal {
		c.JSON(http.StatusOK, gin.H{
			"status":true,
			"msg": "找回成功，请重新设置密码",
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"status":false,
			"msg": "找回失败，密保问题或答案输入有误",
			})
	}
}

// 找回密码后设置新密码
func NewPassword(c *gin.Context){
	var newPassword Newpassword
	err := c.BindJSON(&newPassword)
	if err != nil {
		fmt.Println(err)
		return 
	}
	email := newPassword.Email
	password := newPassword.Password
	rs, err := Db.Exec("UPDATE users SET password=? WHERE email=?",password,email)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(rs)
	status := true
	msg := "设置成功，请登录~"
	c.JSON(http.StatusOK, gin.H{
		"status": status,
		"msg": msg,
	})
}

// 我的简历页面 得到个人简历
func GetResume(c *gin.Context){
	id := c.Query("id")
	var content string
	err := Db.QueryRow("SELECT content FROM resumes WHERE id=?", id).Scan(
		&content,
	   )
	if err != nil {
		fmt.Println(err)
	return
	}

	// 返回数据 第二个参数可以是任意对象 json方法将该对象序列化为json返回 第一个是http状态码
	c.JSON(http.StatusOK, gin.H{
		"status": true,
		"content": content,
	})
}